/*
 * Copyright 2016-2021 Pnoker. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *     http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.xj.business.simulate.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.ie.api.center.manager.feign.DeviceClient;
import com.ie.api.center.manager.feign.DriverClient;
import com.ie.api.center.manager.feign.PointClient;
import com.ie.api.center.manager.feign.TenantClient;
import com.xj.business.simulate.bean.model.ModelContent;
import com.xj.business.simulate.bean.model.ModelData;
import com.xj.business.simulate.service.ModelScheduleService;
import com.xj.business.simulate.service.job.ModelScheduleJob;
import com.xj.common.model.Device;
import com.xj.common.model.Driver;
import com.xj.common.model.Point;
import com.xj.common.model.Tenant;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 模型数据初始化，这里设置定时器进行模型固定时间的更新
 */
@Slf4j
@Service
public class ModelScheduleServiceImpl implements ModelScheduleService {

    @Resource
    private Scheduler scheduler;

    @Resource
    private TenantClient tenantClient;

    @Resource
    private DriverClient driverClient;


    @Resource
    private DeviceClient deviceClient;

    @Resource
    private PointClient pointClient;

    @Resource
    private ModelContent modelContent;

    @Override
    public void initial() {

        installModel();
            //每天凌晨一点执行模型数据的更新 
            createScheduleJobWithCorn("DataScheduleGroup", "ModelScheduleJob", "0 0 1 * * ?", ModelScheduleJob.class);

            try {
                if (!scheduler.isShutdown()) {
                    scheduler.start();
                }
            } catch (SchedulerException e) {
                log.error(e.getMessage(), e);
            }

    }

    @Override
    public void installModel() {
        ModelData modelData = new ModelData();
        modelData.setTenants(tenantClient.list().getData());
        //驱动列表初始化
        Map<Long , List<Driver>> drivers = new HashMap<>();
        for(Tenant tenant : modelData.getTenants()){
            JSONObject jo = new JSONObject();
            jo.put("id",tenant.getId());
            drivers.put(tenant.getId(),driverClient.selectByTenantId(jo).getData());
        }
        modelData.setDrivers(drivers);
        //设备列表初始化
        Map<Long,List<Device>> devices = new HashMap<>();
        for(List<Driver> drivers1 : modelData.getDrivers().values()){
            for(Driver driver : drivers1){
                JSONObject jo = new JSONObject();
                jo.put("driverId",driver.getId());
                devices.put(driver.getId(),deviceClient.selectByDriverId(jo).getData());
            }
        }
        modelData.setDevices(devices);
        //测点列表初始化
        Map<Long ,List<Point>> points = new HashMap<>();
        Map<Long ,Map<String,Point>> pNameToPoints = new HashMap<>();
        Map<Long ,Map<Long,Point>> pidToPoints = new HashMap<>();
        for(List<Device> devices1 : modelData.getDevices().values()){
            for(Device device: devices1){
                //封装points
                JSONObject jo = new JSONObject();
                jo.put("deviceId",device.getId());
                List<Point> pointList = pointClient.selectByDeviceId(jo).getData();
                points.put(device.getId(),pointList);
                //封装pNameToPoints
                Map<String ,Point> mapPoint = new HashMap<>();
                //封装pidToPoints
                Map<Long ,Point> mappidPoint = new HashMap<>();
                for(Point p : pointList){
                    mapPoint.put(p.getName(),p);
                    mappidPoint.put(p.getId(), p);
                }
                pNameToPoints.put(device.getId(),mapPoint);
                pidToPoints.put(device.getId(), mappidPoint);
            }
        }
        //赋值给modedata
        modelData.setPoints(points);
        modelData.setPNameToPoints(pNameToPoints);
        modelData.setPidToPoints(pidToPoints);

        //封装完成
        modelContent.setModelData(modelData);

    }

    /**
     * 创建调度任务
     *
     * @param group    group
     * @param name     name
     * @param corn     corn
     * @param jobClass class
     */
    @SneakyThrows
    public void createScheduleJobWithCorn(String group, String name, String corn, Class<? extends Job> jobClass) {
        JobDetail jobDetail = JobBuilder.newJob(jobClass).withIdentity(name, group).build();
        Trigger trigger = TriggerBuilder.newTrigger()
                .withIdentity(name, group)
                .startAt(DateBuilder.futureDate(1, DateBuilder.IntervalUnit.SECOND))
                .withSchedule(CronScheduleBuilder.cronSchedule(corn))
                .startNow().build();
        scheduler.scheduleJob(jobDetail, trigger);
    }

}
